// 发送请求到后端API
document.getElementById('nameForm').addEventListener('submit', function(e) {
  e.preventDefault();
  const formData = new FormData(this);
  const data = Object.fromEntries(formData.entries());
  
  document.getElementById('loading').style.display = 'block';
  document.getElementById('results').innerHTML = '';
  
  fetch('/api/name/generate', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(data)
  })
  .then(response => response.json())
  .then(result => {
    document.getElementById('loading').style.display = 'none';
    if (result.status === 200) {
      result.data.forEach(name => {
        const item = document.createElement('div');
        item.className = 'result-item';
        item.innerHTML = `
          <h3>${name.name}</h3>
          <p><strong>寓意：</strong>${name.meaning}</p>
          <p><strong>解析：</strong>${name.reason}</p>
          <button data-name="${name.name}">优化此名</button>
        `;
        document.getElementById('results').appendChild(item);
      });
      // 绑定优化按钮事件
      document.querySelectorAll('button[data-name]').forEach(btn => {
        btn.addEventListener('click', function() {
          const currentName = this.getAttribute('data-name');
          data.referenceName = currentName;
          // 重新调用API
          fetch('/api/name/generate', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
          })
          .then(res => res.json())
          .then(optimized => {
            document.getElementById('results').innerHTML = '';
            optimized.data.forEach(n => {
              const optItem = document.createElement('div');
              optItem.className = 'result-item';
              optItem.innerHTML = `
                <h3>${n.name}</h3>
                <p><strong>寓意：</strong>${n.meaning}</p>
                <p><strong>解析：</strong>${n.reason} (基于${currentName}优化)</p>
                <button data-name="${n.name}">继续优化</button>
              `;
              document.getElementById('results').appendChild(optItem);
            });
          });
        });
      });
    } else {
      document.getElementById('results').innerHTML = `<p>错误：${result.message}</p>`;
    }
  })
  .catch(error => {
    document.getElementById('loading').style.display = 'none';
    document.getElementById('results').innerHTML = `<p>请求失败：${error.message}</p>`;
  });
});
